<template>
  <a-cascader
    v-model:value="checkedsValue"
    :options="myOptions"
    placeholder="请选择"
    v-bind="attrs"
  />
</template>
<script setup>
import { useAttrs, ref, computed, toRaw, watch, onMounted } from 'vue'
import { post, get } from 'server/axios'
import { evalPropChain } from 'utils/utils.js'
const emit = defineEmits(['update:value', 'update:options'])

const attrs = useAttrs()
const props = defineProps({
  value: [String, Number, Array],
  url: String,
  // 请求接口参数
  params: {
    type: Object,
    default: () => {
      return {}
    }
  },
  method: {
    type: String,
    default: 'post'
  },
  // 支持自定义传options
  options: {
    type: Array,
    default: () => []
  },
  respField: {
    type: String,
    default: 'data'
  },
  immediate: {
    type: Boolean,
    default: true
  },
  setDisabled: {
    type: Function,
    default: null
  }
})
const AXIOS_METHOD = {
  get: get,
  post: post
}
// 请求接口参数
let reqParams = toRaw(props.params)

const myOptions = ref(props.options || [])

/**
 * 计算双向绑定的值
 */
const checkedsValue = computed({
  get() {
    return props.value
  },
  set(value) {
    emit('update:value', value)
  }
})
const getServeUrl = () => {
  return props.url.startsWith('http')
    ? props.url
    : `${process.env.VUE_APP_CONFIG}/${props.url}`
}

// 拉取options数据
const queryServiceData = async () => {
  const resp = await AXIOS_METHOD[props.method.toLowerCase()](
    getServeUrl(),
    reqParams
  )
  if (resp.success) {
    // eslint-disable-next-line no-eval

    myOptions.value = evalPropChain(resp, props.respField)

    const childrenKey = attrs.fieldNames.children || 'children'
    const deepOption = options => {
      options.map(item => {
        item.disabled = props.setDisabled ? props.setDisabled(item) : undefined
        item[childrenKey]?.length
          ? deepOption(item[childrenKey])
          : (item[childrenKey] = undefined)
      })
    }
    deepOption(myOptions.value)

    emit('update:options', myOptions.value)
  }
}
watch(
  () => props.params,
  (newV, v) => {
    if (JSON.stringify(newV) !== JSON.stringify(v)) {
      if (props.url) {
        reqParams = props.params
        queryServiceData()
      }
    }
  }
)

onMounted(() => {
  if (props.url) {
    props.immediate && queryServiceData()
  }
})
</script>
<style lang="scss" scoped></style>
